package com.uploud.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    public static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg","image/png","image/jpg","image/gif") ;


    @Value("${imagesUrl}")
    private String  baseUrl ;

    @Autowired
    FastFileStorageClient fastFileStorageClient;
    //日志
    private static  final Logger logger = LoggerFactory.getLogger(UploadService.class);

    /**
     * 图片上传
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
//                * 效验文件的大小 （已经在配置文件已经处理了）
        String originalFilename = file.getOriginalFilename();
//                * 效验文件的媒体类型
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            logger.info("文件类型不合法:{}",originalFilename);
            return  null;
        }
//   * 效验文件的内容

        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                logger.info("文件内容不合法:{}",originalFilename);
                return  null;
            }
            //保存到服务器
//            file.transferTo(new File("/Users/zhangyuyang/Desktop/images/"+originalFilename));
            //获取一下图片的后缀名
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            //生成一个完整的路径
            return baseUrl+storePath.getFullPath();

        } catch (IOException e) {
            logger.info("服务器内部错误：{}",originalFilename);
            e.printStackTrace();
        }


        return null;
    }

}
